


var jasper = {reportName:'', changes:{}, elements:{}};




function renderElement(element) {
    jasper.elements[element.key] = element;

    var div = $('<div></div>');
    div.css("display", 'block');
    div.css("position", 'absolute');
    div.css('background-color', '#FFFFFFF');
    div.css('left', element.x);
    div.css('top', element.y);
    div.css('height', element.height);
    div.css('width', element.width);
    div.attr('id', element.key);
    div.attr('active', false);

    console.log("element:" + JSON.stringify(element));

    if (element.type == 'STATIC_TEXT' || element.type == 'TEXT_FIELD') 
        div.text(element.text);
    
    if (element.type == 'TEXT_FIELD') {
        div.css('font-weight', 'bold');
        div.css('font-size', '10px');
    }
    
    else if (element.type == 'LINE') {
        div.css('background-color', '#000000');
    }


    div.appendTo($('#reportDiv'));
    div.on('click', function (e) {
        if(null != jasper.currentDIV) {
            $(jasper.currentDIV).removeClass('ele_active');
        }
        if ('false' == $(this).attr('active')) {
            $(this).attr('active', 'true');
            $(this).addClass('ele_active');
            jasper.currentDIV = $(this);
        }
        else {
            $(this).attr('active', 'false');
            $(this).removeClass('ele_active');
            jasper.currentDIV = null;
        }
        //$(this).attr('active', !(new Boolean($(this).attr('active'))));
        console.log("active:" + $(this).attr('active'));
    });

//            div.keyup(function( event ) {
//                var code = event.keyCode || event.which;
//                console.log('key=' + code);
//                var position = $(this).position();
//                console.log( "position: left: " + position.left + ", top: " + position.top );
//
//                var offset = $(this).offset();
//                console.log( "offset - left: " + offset.left + ", top: " + offset.top );
//            });

}


function renderReport(report) {

    var ctnr = $('#reportContainer');



    ctnr.css('padding-left', report.leftMargin);
    ctnr.css('padding-right', report.rightMargin);

    ctnr.css('padding-top', (report.headerHeight + report.topMargin));

    ctnr.css('padding-bottom', (report.footerHeight + report.bottomMargin) );

    ctnr.css('height', report.pageHeight);
    ctnr.css('width', report.pageWidth);

    var rpt = $('#reportDiv');
    rpt.empty();

    rpt.css('height', report.pageHeight);
    rpt.css('width', report.pageWidth);
    //rpt.css('left', report.leftMargin);
    //rpt.css('top',report.topMargin);

    //Left margin indicator
    var div = $('<div></div>');
    div.css('border-bottom', '1px solid #C1C2FF');
    div.css('position', 'absolute');
    div.css('left', (0 - report.leftMargin));
    div.css('width', report.leftMargin);
    div.text(report.leftMargin);
    div.appendTo($('#reportDiv'));

    //Top margin indicator
    div = $('<div></div>');
    div.css('border-left', '1px solid #C1C2FF');
    div.css('position', 'absolute');
    div.css('height', report.topMargin);
    div.css('left', '20');
    div.css('top', (0 - report.topMargin));
    div.text(report.topMargin);
    div.appendTo($('#reportDiv'));

    //Right margin indicator
    div = $('<div></div>');
    div.css('border-bottom', '1px solid #C1C2FF');
    div.css('position', 'absolute');
    div.css('left', (report.pageWidth));
    div.css('width', report.leftMargin);
    div.text(report.rightMargin);
    div.appendTo($('#reportDiv'));


    //Bottom margin indicator
    div = $('<div></div>');
    div.css('border-left', '1px solid #C1C2FF');
    div.css('position', 'absolute');
    div.css('top', report.pageHeight);
    //div.css('padding-top', (report.footerHeight + report.bottomMargin)/2-5);
    div.css('vertical-align', "middle");
    div.css('height', report.footerHeight + report.bottomMargin);
    div.text(report.footerHeight + report.bottomMargin);

    div.appendTo($('#reportDiv'));






    $.each(report.bands, function (idx, band) {
        $.each(band.elements, function (iidx, element) {
            if(typeof element.key !== "undefined")
                renderElement(element);
            else
                console.log("Hay elementos sin Key");
        });

    });

    //$('body').keyup(
    document.addEventListener('keydown',function (event) {
        if(null == jasper.currentDIV) {
            return;
        }

        var code = event.keyCode || event.which;
        //var code = new Number(keyCode);

        //console.log('key code =' + code);
        if(code > 36 && code < 41) {
            console.log('here');

            if(code == 38) { //up
                console.log('38');
                $(jasper.currentDIV).css('top', ($(jasper.currentDIV).position().top - 1));
            }
            else if(code == 40) { //down
                console.log('40');
                $(jasper.currentDIV).css('top', ($(jasper.currentDIV).position().top  + 1));
            }
            else if(code == 37) { //left
                console.log('37');
                $(jasper.currentDIV).css('left', ($(jasper.currentDIV).position().left - 1));

            }
            else if(code == 39) { //right
                console.log('39');
                $(jasper.currentDIV).css('left', ($(jasper.currentDIV).position().left + 1));
            }
            else {
                console.log("others");
            }
            var key = $(jasper.currentDIV).attr('id');
            var xx = Math.round($(jasper.currentDIV).position().left);
            var yy = Math.round($(jasper.currentDIV).position().top);
            var text = $(jasper.currentDIV).text();
            jasper.changes[key] = {key: key, x: xx, y: yy, text:text};

            event.preventDefault();
        }
    });
}

function loadReport(context, rpt) {
    console.log($.browser.msie);
    $.ajax({
        //dataType: ($.browser.msie) ? 'jsonp' : 'json',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        url: context + '/reportEditor',
        cache: false,
        type: 'GET',
        data:{reportName: rpt },
        success: function (jsonObj) {
            console.log("resultado: " + jsonObj);
            jasper = {reportName: rpt, changes:{}, elements:{}};
            renderReport(jsonObj);

        },
        error: function(jqXHR, textStatus, errorThrown){
                     console.log("Something really bad happened " + textStatus);
                     alert(jqXHR.responseText);
                     alert(errorThrown);
        }
       
    });
}

function saveReport(context) {

    var elements = [];
    for (var i in jasper.changes) {
        if (jasper.changes.hasOwnProperty(i)) {
            elements.push(jasper.changes[i]);
        }
    }


    $.ajax({
        dataType: 'json',
        url: context + '/reportEditor',
        type: 'POST',
        data:{reportName:jasper.reportName, reportConfig: JSON.stringify(elements) },
        success: function (jsonObj) {
            console.log(jsonObj);
            updateMessage();
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log("Something really bad happened " + textStatus);
            alert(jqXHR.responseText);
        }
        /*
        error: function () {
            alert('Ajax readyState: ' + xhr.readyState + '\nstatus: ' + xhr.status + ' ' + err);
        }*/
    });
}


